<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<style>
#console p {
	color:#fff;
}
</style>
<div class="easyui-layout" style="width:100%;height:100%;">
		<div data-options="region:'east',split:true,border:false,iconCls:'icon-order-list'" title="订单列表" style="width:35%;">
			<div class="easyui-layout" style="width:100%;height:100%;">
				<div data-options="region:'north',title:'买进',collapsible:false,iconCls:'icon-buy',tools:'#buyTrades_tool'" style="width:100%;height:50%">
						<table id="buyTrades"></table>
				</div>
				<div data-options="region:'south',split:true,collapsible:false,title:'卖出',iconCls:'icon-sell',tools:'#sellTrades_tool'" style="width:100%;height:50%">
						<table id="sellTrades"></table>
				</div>	
			</div>
		</div>
		<div data-options="region:'center',border:false">
			<div class="easyui-layout" style="width:100%;height:100%;">
				<div data-options="region:'north',title:'任务列表',collapsible:false,border:false,iconCls:'icon-task'" style="width:100%;height:50%">
						<table id="taskList"></table>
				</div>
				<div id="console" data-options="region:'south',split:true,collapsible:false,title:'控制台',iconCls:'icon-console',tools:'#console_tool'" style="width:100%;height:50%;background-color:#21202D;padding-left:10px;padding-right:10px;">
				
				</div>	
			</div>
		
		</div>
</div>

<div id="window_taskEdit"></div>  
<div id="task_list_tool">
	<a href="#" class="easyui-linkbutton" iconCls="icon-add" plain="true" onclick="javascript:addTask()">创建任务</a>
	<a href="#" class="easyui-linkbutton" iconCls="icon-reload" plain="true" onclick="javascript:$('#taskList').datagrid('reload');">刷新</a>
</div>
<div id="console_tool">
	<a href="javascript:void(0)" id="console_clean" iconCls="icon-clean" title="清空控制台" onclick="javascript:$('#console').empty();"></a>
</div>
<div id="buyTrades_tool">
	<a href="javascript:void(0)" iconCls="icon-mymore" title="查看更多" onclick="openTab('trades-list','订单')"></a>
</div>
<div id="sellTrades_tool">
	<a href="javascript:void(0)" iconCls="icon-mymore" title="查看更多" onclick="openTab('trades-list','订单')"></a>
</div>

<script type="text/javascript">

var websocket;

$(function() {
	if('WebSocket' in window) {
		 //websocket = new WebSocket("ws://localhost:8080/socketServer/${sessionScope.user.id }");
		 websocket = new WebSocket("ws://103.255.63.200/socketServer/${sessionScope.user.id }");
    } else if('MozWebSocket' in window) {
          alert("此浏览器只支持MozWebSocket");
    } else {
          alert("此浏览器只支持SockJS");
    }          

 });
 
$('#console_tool #console_clean').tooltip({
	position: 'right',
	content: '<span style="color:#fff">单击清空控制台</span>',
	onShow: function(){
		$(this).tooltip('tip').css({
			backgroundColor: '#666',
			borderColor: '#666'
		});
	}
});

websocket.onopen = function(evnt) {
	 var ps = $("#console").find("p");
	 if(ps.length > 1000){
		 ps[ps.length-1].remove();
	 }
	 if(ps.length <= 0){
 	    $("#console").append("<p>服务器连接成功!</p>")
	 }else{
		 $("<p>服务器连接成功!</p>").insertBefore($("#console").find("p:first"));
		 
	 }
};


websocket.onmessage = function(evnt) {
	if(evnt.data){
		var data = JSON.parse(evnt.data);
		var flag = data.flag;
		if(flag == 'CONSOLE'){
			 var ps = $("#console").find("p");
			 if(ps.length > 1000){
				 ps[ps.length-1].remove();
			 }
			 if(ps.length <= 0){
				$("#console").append("<p>" + data.message + "</p>")
			 }else{
				$("<p>" + data.message + "</p>").insertBefore($("#console").find("p:first"));
			 }
		}else if(flag == "TASK_UPDATE"){
			$('#taskList').datagrid('reload');
		}else if(flag == 'BUY_TRADES_UPDATE'){
			$('#buyTrades').datagrid('load');
		}else if(flag == 'SELL_TRADES_UPDATE'){
			$('#sellTrades').datagrid('load');
			
		}
	}

};

websocket.onerror = function(evnt) {};

websocket.onclose = function(evnt) {
	 var ps = $("#console").find("p");
	 if(ps.length > 1000){
		 ps[ps.length-1].remove();
	 }
	 if(ps.length <= 0){
		$("#console").append("<p>与服务器断开了链接!</p>")
	 }else{
		$("<p>与服务器断开了链接!</p>").insertBefore($("#console").find("p:first"));
	 }
}



	 
	 
function send() {
	 if(websocket != null) {
	      var message = document.getElementById('message').value;
	      console.log(message);
	      websocket.send(message);
	  } else {
	     alert('未与服务器链接.');
	  }
}
function testSocket(){
	$.getJSON("/message/TestWS",{"userId":10000,"message":'helloword'},function(res){
		
	})
}

$('#taskList').datagrid({    
    url:'task/list', 
    method:"get",
    toolbar:"#task_list_tool",
    height:'100%',
    singleSelect:true,
    columns:[[
		{field:'id',title:'操作',halign:'center',width:180,align:'center',formatter : function(value,row,index) {
										var html = ""; 
										if(row.state == '0' || row.state == ''){
											html += "<a style=\"margin:0px 5px;\" href=\"#\" name=\"opera\" class=\"easyui-linkbutton\" data-options=\"iconCls:'icon-start'\" title=\"启动任务\" onclick=\"startTask("+value+")\"></a>";
											html += "<a style=\"margin:0px 5px;\" href=\"#\" name=\"opera\" class=\"easyui-linkbutton\" data-options=\"iconCls:'icon-myedit'\" title=\"修改任务\" onclick=\"editTask("+value+")\"></a>";
											html += "<a style=\"margin:0px 5px;\" href=\"#\" name=\"opera\" class=\"easyui-linkbutton\" data-options=\"iconCls:'icon-sell'\" title=\"一键卖出\" onclick=\"sellById("+value+")\"></a>";
											html += "<a style=\"margin:0px 5px;\" href=\"#\" name=\"opera\" class=\"easyui-linkbutton\" data-options=\"iconCls:'icon-close'\" title=\"关闭任务\" onclick=\"closeTask("+value+")\"></a>";
										}else if(row.state == '1' ){
											html +=  "<a style=\"width:100px;\" href=\"#\" name=\"opera\" class=\"easyui-linkbutton\" data-options=\"iconCls:'icon-stop'\" onclick=\"stopTask("+value+")\">停止任务</a>";
											
										}
										return html;
										
		}},
		{field:'state',title:'当前状态',halign:'center',align:'center',width:70,formatter: function(value,row,index){
			return value == '0' || value == '' ? '已停止' : value == '1' ? '<img style="width:25px;height:25px;"src="/static/images/runing.gif">' : '已关闭';  
		}},
        {field:'symbol',title:'交易对',halign:'center',width:70},    
        {field:'loopCount',title:'交易轮数',halign:'center',align:'center',width:70},
        {field:'buyTradeCount',title:'本轮买入次数',halign:'center',align:'center',width:60},    
        {field:'buyTradeLimit',title:'买入次数上限',halign:'center',align:'center',width:90},    
        {field:'firstMoney',title:'首单购买金额',halign:'center',align:'right',width:100,formatter: function(value,row,index){
											return accounting.format(value,2,',');  
		}},
        {field:'buyLevel',title:'档位',halign:'center',align:'center',width:50},
        {field:'reboundPercent',title:'反弹百分比',halign:'center',align:'right',width:80,formatter: function(value,row,index){
        									return parseFloat(value) == 0 ? '未设置': accounting.format(value,2,',') + "%";    
		}},
        {field:'buyMethod',title:'购买交易策略',halign:'center',align:'center',width:100,formatter: function(value,row,index){
											return value == '1' ? '斐波型' : value == '2' ? '倍投' : '立方倍投';  
		}},
        {field:'profitPercent',title:'止盈百分比',halign:'center',align:'right',width:80,formatter: function(value,row,index){
        									return accounting.format(value,2,',') + "%";    
		}},
		{field:'fallBackPercent',title:'回落百分比',halign:'center',align:'right',width:80,formatter: function(value,row,index){
											return parseFloat(value) == 0 ? '未设置': accounting.format(value,2,',') + "%";    
		}},
        {field:'totalAmount',title:'持仓数量',halign:'center',align:'right',width:100},
        {field:'totalMoney',title:'持仓金额',halign:'center',align:'right',width:100},
        {field:'createTime',title:'创建时间',halign:'center',width:150,formatter: function(value,row,index){
        								return format(value);
								}}
        
    ]],
    onLoadSuccess:function(data){  
        $("a[name='opera']").linkbutton();  
    }
    
}); 



$('#buyTrades').datagrid({    
    url:'trades/buyList', 
    method:"get",
    height:'100%',
    singleSelect:true,
    pagination:true,
    pageSize:20,
    pageList:[20,50,100,200],
    pagePosition:'top',
    columns:[[    
        {field:'tradeTime',title:'交易时间',halign:'center',width:150}, 
        {field:'symbol',title:'交易对',halign:'center',width:70},    
        {field:'tradeType',title:'交易类型',halign:'center',align:'center',width:60,formatter: function(value,row,index){
			return value == '1' ? '市价':'限价';
		}},    
        {field:'money',title:'委托量',halign:'center',align:'right',width:100},
        {field:'amount',title:'成交数量',halign:'center',align:'right',width:100},
        {field:'price',title:'单价',halign:'center',align:'right',width:100},
        {field:'fee',title:'手续费',halign:'center',align:'right',width:100}
    ]]
}); 

$('#sellTrades').datagrid({    
    url:'trades/sellList', 
    method:"get",
    height:'100%',
    singleSelect:true,
    pagination:true,
    pageSize:20,
    pageList:[20,50,100,200],
    pagePosition:'top',
    columns:[[    
        {field:'tradeTime',title:'交易时间',halign:'center',width:150}, 
        {field:'symbol',title:'交易对',halign:'center',width:70},    
        {field:'tradeType',title:'交易类型',halign:'center',align:'center',width:60,formatter: function(value,row,index){
			return value == '1' ? '市价':'限价';
		}},    
        {field:'money',title:'委托量',halign:'center',align:'right',width:100},
        {field:'amount',title:'成交数量',halign:'center',align:'rights',width:100},
        {field:'price',title:'单价',halign:'center',align:'right',width:100},
        {field:'fee',title:'手续费',halign:'center',align:'right',width:100}
    ]]
});

function add0(m){return m<10?'0'+m:m }
function format(shijianchuo){
	//shijianchuo是整数，否则要parseInt转换
	var time = new Date(shijianchuo);
	var y = time.getFullYear();
	var m = time.getMonth()+1;
	var d = time.getDate();
	var h = time.getHours();
	var mm = time.getMinutes();
	var s = time.getSeconds();
	return y+'-'+add0(m)+'-'+add0(d)+' '+add0(h)+':'+add0(mm)+':'+add0(s);
}


function startTask(id){
	$.messager.progress();
	$.post("../scheduler/startTaskById",{id:id},function(res){
		$.messager.progress('close');
		if(res.status == 200){
			
		}else{
			$.messager.alert('提示',res.message,'info');
		}
	})
}		



function closeTask(id){
	$.messager.confirm('关闭任务', '确定要永久关闭当前任务吗？关闭后不可恢复！且未完成的交易不能再继续！', function(r){
		if (r){
			$.messager.progress();
			$.post("../task/closeTask",{id:id},function(res){
				$.messager.progress('close');
				if(res.status == 200){
					$('#taskList').datagrid('reload');
				}else{
					$.messager.alert('提示',res.message,'info');
				}
			})
		}
	});
}


function stopTask(id){
	$.messager.confirm('确认', '确定停止交易吗?', function(r){
		if (r){
			$.messager.progress();
			$.post("../scheduler/stopTaskById",{id:id},function(res){
				$.messager.progress('close');
				if(res.status == 200){
					
				}else{
					$.messager.alert('提示',res.message,'info');
				}
			})
		}
	});
	
}
function sellById(id){
	$.messager.confirm('一键卖出', '确定要卖出当前任务持仓金币吗？', function(r){
		if (r){
			$.messager.progress();
			$.post("../task/sellById",{id:id},function(res){
				$.messager.progress('close');
				if(res.status == 200){
					$('#taskList').datagrid('reload');
					$.messager.alert('成功','操作成功！','info');
				}else{
					$.messager.alert('提示',res.message,'info');
				}
			})
		}
	});
}

function addTask(){
	 $('#window_taskEdit').removeData();
	$('#window_taskEdit').dialog({    
	    title: '创建任务',    
	    width: 600,    
	    height:630,
	    closed: false,    
	    cache: false,
	    resizable:false,
	    minimizable:false,
	    maximizable:false,
	    href: './task-edit',    
	    modal: false,
	    buttons: [{
			text:'保存',
			iconCls:'icon-ok',
			handler:function(){
				taskAdd_submitform(function(){
					$('#taskList').datagrid('reload');
					$("#window_taskEdit").window('close'); 
				});
			}
		},{
			text:'取消',
			handler:function(){
				$("#window_taskEdit").window('close'); 
			}
		}]
	}); 
}


function editTask(id){
	$('#window_taskEdit').data("id",id);
	$('#window_taskEdit').dialog({    
	    title: '修改任务',    
	    width: 600,    
	    height:600,
	    closed: false,    
	    cache: false,
	    resizable:false,
	    minimizable:false,
	    maximizable:false,
	    href: './task-edit',    
	    modal: false,
	    buttons: [{
			text:'保存',
			iconCls:'icon-ok',
			handler:function(){
				taskUpdate_submitform(function(){
					$('#taskList').datagrid('reload');
					$("#window_taskEdit").window('close'); 
				});
			}
		},{
			text:'取消',
			handler:function(){
				$("#window_taskEdit").window('close'); 
			}
		}]
	}); 
}

</script> 